const SERVER_URL = 'https://x.wensixuetang.com'

const randomStr = function (len) {
  len = len || 32;
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}

const guid = function () {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}

const formatTime = date => {
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [hour, minute].map(formatNumber).join(':')
}

const formatDate = function (date, days = 0) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return [year, month, day + days].map(formatNumber).join('-')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const time = function () {
  //获取当前时间戳  
  var timestamp = Date.parse(new Date());
  timestamp = timestamp / 1000;
  return timestamp
  // console.log("当前时间戳为：" + timestamp);
}

//会话管理
const expire = function (e, path = undefined, paths) {
  //放过页面, 某些页面不需要登录可以查看
  var power = false
  for (var k = 0; k < paths.length; k++) {
    console.log('鉴权', path, paths[k])
    if (path == paths[k]) {
      power = false
      return
    }
  }

  //判断是否有登录, 如果无登录, 则返回首页
  if (e == 0) {
    goTo('/pages/index/index', 2)
    return
  }

  //未登录或登录超时均跳到首页
  if (time() - e >= 1800) {
    goTo('/pages/index/index', 2)
    // goTo('', 3)
    showMsg('登录超时')
  }

  if (!power) {//权限鉴别
    //没有权限
    goTo('/pages/index/index', 2)
    return
  }
}

const checkPhone = function (phone) {
  if (!(/^1[34578]\d{9}$/.test(phone))) {
    return false
  }
  return true
}

const getOpenId = function (type, success, fail) {
  wx.login({
    success: function (res) {
      if (res.code) {
        //发起网络请求
        // httpGet('/onLogin?code=' + res.code, function (res) {
        //   success(res)
        // })
        httpPost('/onLogin?code=' + res.code, { s: type }, success)
      } else {
        console.log('获取用户登录态失败！' + res.errMsg)
        return false
      }
    },
    fail: function (res) { fail }
  })
}

const showMsg = function (title) {
  wx.showLoading({
    title: title,
    mask: true,
    success: function (res) { },
    fail: function (res) { },
    complete: function (res) { },
  })
  setTimeout(function () {
    wx.hideLoading()
  }, 500)
}

const goTo = function (url, mode) {
  if (mode === 1 || mode == null) {//跳转到某个页面
    wx.navigateTo({
      url: url
    })
  } else if (mode === 2) {//关闭所有页面,打开当前页面
    wx.reLaunch({
      url: url
    })
  } else if (mode === 3) {//返回页面层级
    wx.navigateBack({
      delta: (url ? url : 10) //url 默认返回首页
    })
  }
}

const showToast = function (title, icon = 1) {
  wx.showToast({
    title: title,
    icon: icon === 1 ? 'success' : 'loading',
    duration: 2000,
    mask: true,
    success: function (res) { },
    fail: function (res) { },
    complete: function (res) { },
  })
}

const showLoading = function (title) {
  wx.showLoading({
    title: title,
    mask: true,
    success: function (res) { },
    fail: function (res) { },
    complete: function (res) { },
  })
}

const showModal = function (title, msg, cancelText, confirmText, success, fail, complete) {
  wx.showModal({
    title: title,
    content: msg,
    showCancel: true,
    cancelText: cancelText === undefined ? '重试' : cancelText,
    cancelColor: 'red',
    confirmText: confirmText === undefined ? '关闭' : confirmText,
    confirmColor: '#3CC51F',
    success: function (res) { success !== undefined ? success(res) : null },
    fail: function (res) { fail !== undefined ? fail(res) : null },
    complete: function (res) { complete !== undefined ? complete(res) : null },
  })
}

const showMenu = function (menu, success) {
  wx.showActionSheet({
    itemList: menu,
    success: function (res) { success !== undefined ? success(res) : null },
    fail: function (res) { },
    complete: function (res) { },
  })
}

const httpGet = function (url, success, fail, complete) {
  wx.request({
    url: SERVER_URL + url,
    method: 'GET',
    dataType: 'json',
    success: function (res) { success !== undefined ? success(res) : null },
    fail: function (res) { fail !== undefined ? fail(res) : null },
    complete: function (res) { complete !== undefined ? complete(res) : null },
  })
}

const httpPost = function (url, data, success, fail, complete) {
  wx.request({
    url: SERVER_URL + url,
    data: data,
    // header: header,
    method: 'POST',
    dataType: 'json',
    // success: function (res) { success !== undefined ? success(res) : null },
    success: function (res) { typeof success == 'function' && success(res) },
    fail: function (res) { fail !== undefined ? fail(res) : null },
    complete: function (res) { complete !== undefined ? complete(res) : null },
  })
}

// const requestTask = wx.request({
//   url: 'https://www.wensixuetang.com/test/2', //仅为示例，并非真实的接口地址
//   data: {
//     x: '',
//     y: ''
//   },
//   header: {
//     'content-type': 'application/json'
//   },
//   success: function (res) {
//     console.log(res.data)
//   }
// })

// requestTask.abort() // 取消请求任务


//获取用户信息
const getUserInfo = function (e) {
  wx.getUserInfo({
    success: function (res) {
      var userInfo = res.userInfo
      pushUserInfo(res.userInfo, e.openId)
      var nickName = userInfo.nickName
      var avatarUrl = userInfo.avatarUrl
      var gender = userInfo.gender //性别 0：未知、1：男、2：女
      var province = userInfo.province
      var city = userInfo.city
      var country = userInfo.country
      e.userInfo = userInfo
      // console.log(userInfo, nickName, avatarUrl, gender, province, city, country)
    }
  })
}

//提交用户信息到后台
const pushUserInfo = function (data, openid) {
  httpPost('/login/pushuserinfo', { o: openid, d: data })
}

//获取学校信息
const getSchoolInfo = function (data, success) {
  httpPost('/public/getSchoolInfo', data, success)
}

//获取班级信息
const getGradeInfo = function (data, success) {
  httpPost('/public/getGradeInfo', data, success)
}

//获取小区信息
const getPosInfo = function (success) {
  httpGet('/public/getPosInfo', typeof success == 'function' && success)
}

//获取班级学生信息
const getStudentInfo = function (e, c, k, success) {
  httpPost('/public/getInfo', { type: 'student', kecheng: k, grade: e, class: c }, typeof success == 'function' && success)
}

//获取教务资源,老师\课程\课时
const getResourcesInfo = function (data, success) {
  httpPost('/teach/getResourcesInfo', data, typeof success == 'function' && success)
}

//修改资源信息
const modifyResourcesInfo = function (data, success) {
  httpPost('/teach/modifyResourcesInfo', data, typeof success == 'function' && success)
}

//获取班级学生信息
const getStudentInfo_ex = function (e, success) {
  httpPost('/public/getInfo', { "type": "info", "id": e }, typeof success == 'function' && success)
}

const pushStudentInfo = function (e, success) {
  httpPost('/public/getInfo', e, typeof success == 'function' && success)
}

const pushTeachInfo = function (data, success) {
  httpPost('/course/pushTeachInfo', data, typeof success == 'function' && success)
}

const pushOutlineInfo = function (data, success) {
  httpPost('/course/pushoutlineinfo', data, typeof success == 'function' && success)
}

const addClassInfo = function (data, success) {
  httpPost('/course/addclassinfo', data, typeof success == 'function' && success)
}

const pushclassinfo = function (data, success) {
  httpPost('/course/pushclassinfo', data, typeof success == 'function' && success)
}

const addCourseInfo = function (data, success) {
  httpPost('/course/addcourseinfo', data, typeof success == 'function' && success)
}

const modifyCourseInfo = function (data, success) {
  httpPost('/course/modifycourseinfo', data, typeof success == 'function' && success)
}

const surplusCourseInfo = function (data, success) {
  httpPost('/course/surplusCourseInfo', data, typeof success == 'function' && success)
}

const modifyStudentInfo = function (data, success) {
  httpPost('/manage/modifystudent', data, typeof success == 'function' && success)
}

const delStudentInfo = function (data, success) {
  httpPost('/manage/delclassinfo', data, typeof success == 'function' && success)
}

const getTenant = function (callback) {
  httpGet('/public/gettenant', typeof success == 'function' && success)
}

const getCourseInfo = function (data, callback) {
  httpPost('/public/getCourseInfo', data, typeof success == 'function' && success)
}

const getClassInfo = function (data, success) {
  httpPost('/course/getclassinfo', data, typeof success == 'function' && success)
}

const getClassDetail = function (data, success) {
  httpPost('/course/getclassdetail', data, typeof success == 'function' && success)
}

const checkIn = function (data, success) {
  httpPost('/user/checkininfo', data, typeof success == 'function' && success)
}

const checkInInfo = function (data, success) {
  httpPost('/user/checkininfo', { type: 'get', id: data }, typeof success == 'function' && success)
}

const checkInList = function (data, like, success) {
  httpPost('/user/checkininfo', { type: 'list', id: data, like: like }, typeof success == 'function' && success)
}

const getActiveList = function (success) {
  httpPost('/xcx/active/getactivelist', { type: 'list' }, typeof success == 'function' && success)
}

const getActiveDetail = function (data, success) {
  httpPost('/xcx/active/getactivedetail', { type: 'detail', id: data }, typeof success == 'function' && success)
}

const createActiveDetail = function (data, success) {
  httpPost('/xcx/active/createActiveInfo', { type: 'add', data: data }, typeof success == 'function' && success)
}

const modifyActiveDetail = function (data, success) {
  httpPost('/xcx/active/modifyActiveInfo', { type: 'info', data: data }, typeof success == 'function' && success)
}

const updateActiveDetail = function (type, aid, success) {
  //type = share , join , look
  httpPost('/xcx/active/updateActiveInfo', { type: type, aid: aid }, typeof success == 'function' && success)
}

const joinActiveInfo = function (data, success) {
  httpPost('/xcx/active/joinActiveInfo', { type: 'join', data: data }, typeof success == 'function' && success)
}

const setdTemplateMsg = function (openId, token, formId, success) {
  httpPost('/xcx/active/sendTemplateMsg', { oid: openId, t: token, i: formId }, typeof success == 'function' && success)
}

const getWxaCodeUnlimit = function (token, success) {
  httpPost('/xcx/qrcode/getWxaCodeUnlimit', { t: token }, typeof success == 'function' && success)
}

//获取支付ID
const getPayId = function (tenant, openid, fee, detail, s, success) {
  httpPost('/pay/unifiedorder', { t: tenant, fee: fee, openid: openid, detail: detail, s: s }, typeof success == 'function' && success)
}

const getcontactlist = function (success) {
  httpGet('/contact/getcontactlist', typeof success == 'function' && success)
}

const getMsgList = function (data, success) {
  httpPost('/contact/getmsglist', data, typeof success == 'function' && success)
}

module.exports = {
  //基础库类
  guid: guid,
  time: time,
  expire: expire,
  httpGet: httpGet,
  httpPost: httpPost,
  formatTime: formatTime,
  formatDate: formatDate,
  checkPhone: checkPhone,
  randomStr: randomStr,
  showMsg: showMsg,
  showMenu: showMenu,
  goTo: goTo,
  showToast: showToast,
  showLoading: showLoading,
  showModal: showModal,
  checkIn: checkIn,
  checkInInfo: checkInInfo,
  checkInList: checkInList,
  getOpenId: getOpenId,
  getResourcesInfo: getResourcesInfo,
  modifyResourcesInfo: modifyResourcesInfo,
  getUserInfo: getUserInfo,
  pushUserInfo: pushUserInfo,
  getGradeInfo: getGradeInfo,
  getStudentInfo: getStudentInfo,
  pushStudentInfo: pushStudentInfo,
  getStudentInfo_ex: getStudentInfo_ex,
  pushTeachInfo: pushTeachInfo,
  pushOutlineInfo: pushOutlineInfo,
  getTenant: getTenant,
  getSchoolInfo: getSchoolInfo,
  getPosInfo: getPosInfo,
  getCourseInfo: getCourseInfo,
  addCourseInfo: addCourseInfo,
  surplusCourseInfo: surplusCourseInfo,
  modifyCourseInfo: modifyCourseInfo,
  modifyStudentInfo: modifyStudentInfo,
  addClassInfo: addClassInfo,
  pushclassinfo: pushclassinfo,
  delStudentInfo: delStudentInfo,
  getClassInfo: getClassInfo,
  getClassDetail: getClassDetail,
  //活动相关
  getActiveList: getActiveList,
  getActiveDetail: getActiveDetail,
  createActiveDetail: createActiveDetail,
  modifyActiveDetail: modifyActiveDetail,
  updateActiveDetail: updateActiveDetail,
  joinActiveInfo: joinActiveInfo,
  setdTemplateMsg: setdTemplateMsg,
  //获取小程序二维码
  getWxaCodeUnlimit: getWxaCodeUnlimit,
  // requestTask: requestTask
  getPayId: getPayId,

  //获取客服消息
  getcontactlist: getcontactlist,
  getMsgList: getMsgList,
}